#!/bin/bash
# Start script for Jim - The Java Image Manager
# 


f_find_java() {
    # Try using preset JAVA_HOME
    if [ "${JAVA_HOME}" ] ; then
       JIM_JAVA_BIN=${JAVA_HOME}/bin/java
       if [ ! -x ${JIM_JAVA_BIN} ] ; then
          JIM_JAVA_BIN=""
       fi
    fi

    # Try using java on Path
    if [ ! "${JIM_JAVA_BIN}" ] ; then
       JIM_JAVA_BIN=`which java`
       if [ $? -eq 0 ] ; then 
          JIM_JAVA_BIN=`readlink -f ${JIM_JAVA_BIN}`
       fi
    fi    
}

JIM_USER=${HOME}/.jim
if [ ! -d "${JIM_USER}" ] ; then
    mkdir ${JIM_USER}
fi

JIM_LAUNCH_CONF=${JIM_USER}/launch.conf
if [ -f "${JIM_LAUNCH_CONF}" ] ; then
    . ${JIM_LAUNCH_CONF}
else
   # Try to create a launch script
   cat > "${JIM_LAUNCH_CONF}" << EOF
# Jim Launch configuration.
# Location of Java. Blank to autodetect.
# JAVA_HOME=
# Max Heap size to allocation to JAVA_VM
# JIM_MAX_MEMORY=256M
# VM properties
# JIM_JAVA_OPTS="-Djim.user.home=${HOME}/.jim"

EOF
  [ -f "${JIM_LAUNCH_CONF}" ] && echo "${JIM_LAUNCH_CONF} created." 
fi

if [ ! "${JIM_MAX_MEMORY}" ] ; then
   JIM_MAX_MEMORY=256M
fi

JIM_SCRIPT=$0
if [ -h "${JIM_SCRIPT}" ] ; then
   JIM_SCRIPT=`readlink -f "$0"`
fi

JIM_HOME=`dirname ${JIM_SCRIPT}`
JIM_CLASSPATH=
cp_sep=
for jar in $JIM_HOME/*.jar
do
    echo ${jar}
	JIM_CLASSPATH="${JIM_CLASSPATH}${cp_sep}${jar}"
	cp_sep=":"
done
echo "$JIM_CLASSPATH"

f_find_java

if [ ! -x ${JIM_JAVA_BIN} ] ; then 
  echo "Can't find a java runtime. Set JAVA_HOME"
fi


echo "Running Jim using ${JIM_JAVA_BIN} -X${JIM_MAX_MEMORY}"

${JIM_JAVA_BIN} -Xmx${JIM_MAX_MEMORY} -cp ${JIM_CLASSPATH} ${JIM_JAVA_OPTS} au.com.lastweekend.jim.Jim
